package club.smartdot.hash;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import club.smartdot.util.RedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisHash {
	public static void main(String[] args) {
		// 创建连接池
		JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
		Jedis jedis = null;
		try {
			// 从连接池中获取Jedis对象
			jedis = pool.getResource();
			// 设置hash类型。key:loginuser, filed：username，value: zhangsan
			jedis.hset("loginuser", "username", "zhangsan");
			System.out.println("username的值:" + jedis.hget("loginuser", "username"));
			
			// 设置多个值
			Map<String, String> map = new HashMap<>();
			map.put("username", "caifenglin");
			map.put("age", "26");
			map.put("website", "www.smartdot.club");
			jedis.hmset("logininfo", map);
			// 从Redis取hash数据
			List<String> fieldValues = jedis.hmget("logininfo", "username", "website");
			for (String fv : fieldValues) {
				System.out.println("filed值:" + fv);
			}
			
			// 存在username吗?
			System.out.println("返回boolean,存在username:" + jedis.hexists("logininfo", "username"));
			// 查看所有的field
			Set<String> set = jedis.hkeys("logininfo");
			Iterator<String> iterator = set.iterator();
			while(iterator.hasNext()) {
				System.out.println("field name:" + iterator.next());
			}
			// 删除field:age
			jedis.hdel("logininfo", "age");
			// 获取age
			System.out.println("age是null:" + jedis.hget("logininfo", "age"));
			// 所有field的数量
			System.out.println("field个数:" + jedis.hlen("logininfo"));
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(jedis != null) {
				// 使用完的连接池对象，放回连接池
				jedis.close();
			}
		}
		
	}
}
